package org.example.testcode.helper;

import org.example.testcode.bean.TopicEsInfo;
import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TopicHelper {


    /**
     * 获取所有作者RSS
     *
     * @return
     */
    public static List<String> allAuthorRss() {
        String url = "https://www.cnblogs.com/VincentLee/p/12868735.html"; // id=mainContent
        //url = "https://www.cnblogs.com/me-sa/default.html?page=1";  //id=main
        url = "https://www.cnblogs.com/AllBloggers.aspx";
        List<TopicEsInfo> topicList = new ArrayList<>();

        //拿到作者的用户名
        String username = url.substring(url.indexOf(".com/") + 5);
        if (username.contains("/p/")) {
            username = username.substring(0, username.indexOf("/p/"));
        }

        //作者博客第一页
        String pageUrl = String.format("https://www.cnblogs.com/%s/default.html?page=1", username);

        //作者RSS地址
        pageUrl = String.format("https://www.cnblogs.com/%s/rss", username);

        //所有用户的博客的列表页
        pageUrl = "https://www.cnblogs.com/AllBloggers.aspx";

        Document document = null;
        try {
            document = Jsoup.connect(pageUrl).get();
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
        2. Document：文档对象。代表内存中的dom树
                * 获取Element对象

                * getElementById​(String id)：根据id属性值获取唯一的element对象
                * getElementsByTag​(String tagName)：根据标签名称获取元素对象集合
                * getElementsByAttribute​(String key)：根据属性名称获取元素对象集合
                * getElementsByAttributeValue​(String key, String value)：根据对应的属性名和属性值获取元素对象集合
        3. Elements：元素Element对象的集合。可以当做 ArrayList<Element>来使用
        4. Element：元素对象
        1. 获取子元素对象

                * getElementById​(String id)：根据id属性值获取唯一的element对象
                * getElementsByTag​(String tagName)：根据标签名称获取元素对象集合
                * getElementsByAttribute​(String key)：根据属性名称获取元素对象集合
                * getElementsByAttributeValue​(String key, String value)：根据对应的属性名和属性值获取元素对象集合
        */
        if (null == document) {
            System.out.println("网络获取数据失败");
            return null;
        }
        Elements postItems = document.getElementsByTag("a");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //循环处理
        List<String> rssList = new ArrayList<>();
        for (Element postItem : postItems) {
            if (null != postItem.attributes() && postItem.hasAttr("href") &&
                    postItem.attr("href").contains("/rss/")) {
                if (!rssList.contains(postItem.attr("href"))) {
                    rssList.add(postItem.attr("href"));
                }
            }
        }

        return rssList;
    }

    /**
     * 通过作者Rss地址获取最新topic
     *
     * @param authorRssUrl
     * @return
     */
    public static List<TopicEsInfo> getTopicByAuthorRss(String authorRssUrl) {
        String url = "https://www.cnblogs.com/VincentLee/p/12868735.html"; // id=mainContent
        //url = "https://www.cnblogs.com/me-sa/default.html?page=1";  //id=main
        List<TopicEsInfo> topicList = new ArrayList<>();

        //拿到作者的用户名
        String username = url.substring(url.indexOf(".com/") + 5);
        if (username.contains("/p/")) {
            username = username.substring(0, username.indexOf("/p/"));
        }

        //作者博客第一页
        String pageUrl = String.format("https://www.cnblogs.com/%s/default.html?page=1", username);

        //作者RSS地址
        pageUrl = String.format("https://www.cnblogs.com/%s/rss", username);

        pageUrl = authorRssUrl;

        Document document = null;
        try {
            document = Jsoup.connect(pageUrl).get();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Elements postItems = document.getElementsByTag("entry");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //循环处理每篇博客
        for (Element postItem : postItems) {
            TopicEsInfo topic = new TopicEsInfo();
            topic.setLink(postItem.getElementsByTag("id").first().text().trim());

            //TODO：根据原文链接生成文档ID
            if (null == topic.getLink() || topic.getLink().length() < 1) {
                continue;
            }
            topic.setDocId(MD5Helper.GetTopicUnionId(topic.getLink()));

            topic.setTitle(postItem.getElementsByTag("title").first().text().trim());
            topic.setNavText(postItem.getElementsByTag("summary").first().text().trim());
            topic.setAuthor(document.getElementsByTag("author").first().child(0).text().trim());
            try {
                Date tmpDate = sdf.parse(postItem.getElementsByTag("published").first().text()
                        .trim().replace("T", " ").replace("Z", " ").trim());
                topic.setPostTime(sdf.format(tmpDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            topic.setSource("cnblog");
            topicList.add(topic);

        }
        return topicList;
    }

    public static String notTopicImg = "images/xml.gif;/images/logo.svg;/search.svg;/newpost.svg;/myblog.svg;/message.svg" +
            ";/lite-mode-on.svg;/avatar-default.svg;/xml.gif;/lite-mode-check.svg;https://camo.githubusercontent.com/;/copycode.gif";

    /**
     * 通过链接获取话题内容，不包含标题和作者时间
     *
     * @param link
     * @return
     */
    public static TopicEsInfo getCNBlogByLink(String link) {
        Document document = null;
        try {
            document = Jsoup.connect(link).header("Accept", "*/*")
                    .header("Accept-Encoding", "gzip, deflate")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
                    .timeout(10000).get();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        //正文内容：cnblogs_post_body
        TopicEsInfo topic = new TopicEsInfo();
        //topic.setLink(link);
        //topic.setDocId(MD5Helper.GetTopicUnionId(topic.getLink()));

        Element cnblogs_post_body = null;
        try {
            cnblogs_post_body = document.getElementById("cnblogs_post_body");
        } catch (Exception ex) {
        }
        if (null == cnblogs_post_body) {
            return null;
        }
        topic.setBodyText(cnblogs_post_body.text());

        Elements imgItems = document.getElementsByTag("img");
        String[] notTopicArr = notTopicImg.split(";");
        if (null != imgItems && imgItems.size() > 0) {
            int imgCount = 0;
            for (Element imgItem : imgItems) {
                String tmpImg = imgItem.attr("src");
                if (!tmpImg.contains("http")) {
                    continue;
                }


                //过滤哪些不是博客的截图图片
                boolean isNotTopicImg = false;
                if (null != tmpImg && tmpImg.length() > 0) {
                    for (String notImg : notTopicArr) {
                        if (tmpImg.contains(notImg)) {
                            isNotTopicImg = true;
                            break;
                        }
                    }
                }

                //记录图片
                if (!isNotTopicImg) {
                    if (imgCount < 1) {
                        topic.setPicUrl(tmpImg);
                    } else {
                        topic.setPicUrl2((topic.getPicUrl2() == null ? "" : topic.getPicUrl2()) + ";" + tmpImg);

                    }
                    imgCount++;
                    if (null != topic.getPicUrl2()) {
                        if (topic.getPicUrl2().startsWith(";")) {
                            topic.setPicUrl2(topic.getPicUrl2().substring(1));
                        }
                    }
                }

            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return topic;
    }

}
